//app.js
import { requestdata } from "./utils/request/baserequest"
import { update_info, get_openid } from "./utils/request/request_json"
App({
    onLaunch: function() {
        var self = this;
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)
        self.login();
    },
    login(callback) {
        var self = this;
        // 登录
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                if (res.code) {
                    //发起网络请求
                    var data = {
                        jscode: res.code,
                    }
                    get_openid(data, function(success) {
                        var res = JSON.parse(success.data.data);
                        self.globalData.opid = res.openid;
                        callback ? callback() : "";
                    }, function(res) {
                    })
                } else {
                    wx.showToast({
                        title: '登录失败，请重试',
                        icon: 'loading',
                        duration: 2000
                    })
                    console.log('获取用户登录态失败！' + res.errMsg)
                }
            }
        })
    },
    getUserAuth(Dialog, callback, sucscallback) {
        var self = this;
        wx.getUserInfo({
            lang:"zh_CN",
            success: function(res) {
                self.update_info(res.userInfo);
                sucscallback ? sucscallback(res) : '';
            },
            fail: function(res) {
                self.getNewUser(Dialog, callback);
            }
        })
    },
    getNewUser(Dialog, callback) {
        var that = this;
        Dialog({
            title: '微信授权',
            showImage: '../../pages/image/0.png',
            showMessage: "明信申请获得以下权力",
            message: '获得你的公开信息(昵称、头像等)',
            selector: '#dialogUser'
        }).then((res) => {

            that.update_info(res.data);
            callback ? callback() : "";
        });
    },
    //更新用户接口
    update_info(res) {
        var that = this;
        var data = {
            openid: that.globalData.opid,
            nickName: res.nickName,
            avatarUrl: res.avatarUrl,
            gender: res.gender.toString(),
            city: res.city,
            province: res.province,
            country: res.country,
            language: res.language,
        }
        update_info(data, function(res) { })
            // that.requestdata("POST", data, "wx/update_info", function(res) {})
    },
    //公共data
    globalData: {
        userInfo: null,
        baseimg: "",
        opid: "",
        pageIdx: 0,
    }
})